package com.msb.mall.product.service.impl;

import com.msb.mall.product.config.MyThreadPoolConfig;
import com.msb.mall.product.entity.SkuImagesEntity;
import com.msb.mall.product.entity.SkuInfoEntity;
import com.msb.mall.product.entity.SpuInfoDescEntity;
import com.msb.mall.product.service.*;
import com.msb.mall.product.vo.SkuItemSaleAttrVo;
import com.msb.mall.product.vo.SpuItemGroupAttrVo;
import com.msb.mall.product.vo.SpuItemVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.msb.common.utils.PageUtils;
import com.msb.common.utils.Query;

import com.msb.mall.product.dao.SkuInfoDao;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    AttrGroupService attrGroupService;

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    ThreadPoolExecutor  threadPoolExecutor;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }


     // page=1&limit=10&key=&catelogId=0&brandId=0&min=0&max=0
    /**
     * SKU 信息检索的方法
     * 类别
     * 品牌
     * 价格区间
     * 检索的关键字
     * 分页查询
     * page=1&limit=10&key=&catelogId=0&brandId=0&min=0&max=0
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {

        QueryWrapper<SkuInfoEntity> Wrapper = new QueryWrapper<>();
        //检索的关键字key
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            Wrapper.and((m)->{
                m.eq("sku_id", key).or().like("sku_name", key);
            });
        }
        //catelogId
        String catalogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catalogId) && !"0".equalsIgnoreCase(catalogId)) {
            Wrapper.eq("catalog_id", catalogId);
        }


        //brandId
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            Wrapper.eq("brand_id", brandId);
        }

        //min&max 在多少价格之间
        String min = (String) params.get("min");
        if (!StringUtils.isEmpty(min)) {
            Wrapper.ge("price", min);
        }
        String max = (String) params.get("max");
        if (!StringUtils.isEmpty(max)) {
            try {
                // 如果max=0那么我们也不需要加这个条件
                BigDecimal bigDecimal = new BigDecimal(max);
                if (bigDecimal.compareTo(new BigDecimal(0)) == 1) {
                    // 说明 max > 0 要是不大于0就不会走这个分支
                    Wrapper.le("price", max);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                Wrapper);


        return new PageUtils(page);
    }

    /**
     * 根据spuId找到对应的sku的相关信息
     * @param spuId
     * @return
     */
    @Override
    public List<SkuInfoEntity> getskusByspu(Long spuId) {

        List<SkuInfoEntity> skuInfoEntities = this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));

        return skuInfoEntities;
    }

    @Override
    public SpuItemVO item(Long skuId)  {

        SpuItemVO VO = new SpuItemVO();
        CompletableFuture<SkuInfoEntity> skuInfoFuture = CompletableFuture.supplyAsync(() -> {
            // 1.sku的基本信息 pms_sku_info
            SkuInfoEntity skuInfoEntity = this.getById(skuId);
            VO.setInfo(skuInfoEntity);
            return skuInfoEntity;
        }, threadPoolExecutor);

        CompletableFuture<Void> imagesFuture = CompletableFuture.runAsync(() -> {
            // 2.sku的图片信息pms_sku_images
            List<SkuImagesEntity> skuImagesEntities = skuImagesService.getImagesBySkuId(skuId);
            VO.setImages(skuImagesEntities);
        }, threadPoolExecutor);

        final CompletableFuture<Void> saleFuture = skuInfoFuture.thenAcceptAsync((res) -> {
            // 3.获取spu中的销售属性的组合
            List<SkuItemSaleAttrVo> skuItemSaleAttrVos = skuSaleAttrValueService.getSkuSaleAttrValueBySpuId(res.getSpuId());
            VO.setSaleAttrs(skuItemSaleAttrVos);
        }, threadPoolExecutor);


        final CompletableFuture<Void> spuFuture = skuInfoFuture.thenAcceptAsync((res) -> {
            // 4.获取SPU的介绍
            SpuInfoDescEntity spuInfoDescServiceById = spuInfoDescService.getById(res.getSpuId());
            VO.setDesc(spuInfoDescServiceById);
        }, threadPoolExecutor);

        final CompletableFuture<Void> groupFuture = skuInfoFuture.thenAcceptAsync((res) -> {
            // 5.获取SPU的规格参数
            List<SpuItemGroupAttrVo> spuItemGroupAttrVoList = attrGroupService.getAttrgroupWithSpuId(res.getCatalogId(),res.getSpuId());
            VO.setBaseAttrs(spuItemGroupAttrVoList);

        }, threadPoolExecutor);

        try {
            //这里阻塞，等待上面完成，最后再返回
            CompletableFuture.allOf(imagesFuture, saleFuture, spuFuture, groupFuture).get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }


        return VO;
    }

    @Override
    public List<String> getSkuSaleAttrs(Long skuId) {

        return baseMapper.getSkuSaleAttrs(skuId);
    }
}